/* Includes ----------------------------------------------------------------- */
#include "../bsp/bsp_spi.h"

#include <gpio.h>
#include <spi.h>

#include "../bsp/bsp_tim.h"
/* Private define ----------------------------------------------------------- */
/* Private macro ------------------------------------------------------------ */
/* Private typedef ---------------------------------------------------------- */
#define ICM20602_SPI_W 0x00
#define ICM20602_SPI_R 0x80
/* Private variables -------------------------------------------------------- */
/* Private function  -------------------------------------------------------- */
/**
 * @brief 写字节
 *
 * @param cmd 地址
 * @param val 数据
 */
void Bsp_SPI_WriteByte(uint8_t cmd, uint8_t val) {
  uint8_t dat[2];
  /* 片选 */
  HAL_GPIO_WritePin(MPU_CS_GPIO_Port, MPU_CS_Pin, GPIO_PIN_RESET);

  /* 写指令 */
  dat[0] = cmd | ICM20602_SPI_W;
  dat[1] = val;
  HAL_SPI_Transmit(&hspi1, dat, 2, 500);

  /* 片选 */
  HAL_GPIO_WritePin(MPU_CS_GPIO_Port, MPU_CS_Pin, GPIO_PIN_SET);
}

/**
 * @brief 读字节
 *
 * @param cmd 地址
 * @param val 数据
 */
void Bsp_SPI_ReadByte(uint8_t cmd, uint8_t *val) {
  uint8_t dat[2];
  /* 片选 */
  HAL_GPIO_WritePin(MPU_CS_GPIO_Port, MPU_CS_Pin, GPIO_PIN_RESET);

  /* 读指令 */
  dat[0] = cmd | ICM20602_SPI_R;
  dat[1] = *val;
  HAL_SPI_TransmitReceive(&hspi1, dat, dat, 2, 500);

  /* 片选 */
  HAL_GPIO_WritePin(MPU_CS_GPIO_Port, MPU_CS_Pin, GPIO_PIN_SET);

  *val = dat[1];
}

/**
 * @brief 读多字节
 *
 * @param val 数据
 * @param num 个数
 */
void Bsp_SPI_ReadBytes(uint8_t *val, uint8_t num) {
  /* 片选 */
  HAL_GPIO_WritePin(MPU_CS_GPIO_Port, MPU_CS_Pin, GPIO_PIN_RESET);
  /* 读多字节 */
  HAL_SPI_TransmitReceive(&hspi1, val, val, num, 500);
  /* 片选 */
  HAL_GPIO_WritePin(MPU_CS_GPIO_Port, MPU_CS_Pin, GPIO_PIN_SET);
}
